
import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/constant/constant.dart';
import 'package:flutter_ncsjqz_getx/http/dio_service.dart';
import 'package:flutter_ncsjqz_getx/model/base_entity.dart';
import 'package:flutter_ncsjqz_getx/page/my/message/message_info_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/chat_setting/private/chat_setting_view.dart';
import 'package:flutter_ncsjqz_getx/page/square/release/release_view.dart';
import 'package:flutter_ncsjqz_getx/util/toast_util.dart';
import 'package:flutter_ncsjqz_getx/widget/base_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/gradient_button.dart';
import 'package:flutter_ncsjqz_getx/widget/ink_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/input_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/row_line_widget.dart';
import 'package:flutter_ncsjqz_getx/widget/tab_widget.dart';
import 'package:flutter_show_img_package/show_image_widget.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';

import 'details/guang_chang_details_view.dart';
import 'square_logic.dart';

/// <summary>
/// todo: 广场
/// author：zwb
/// dateTime： 2021/11/30 15:31
/// filePath： lib/page/square/square_view.dart
/// desc:
/// <summary>
///
class SquarePage extends StatefulWidget {
  @override
  _SquarePageState createState() => _SquarePageState();
}

class _SquarePageState extends State<SquarePage> {
  final logic = Get.put(SquareLogic());

  @override
  void initState() {
    super.initState();
    logic.getData();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SquareLogic>(
      builder: (controller) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Column(
            children: [

              _searchBar(),

              _contentBody()
            ],
          ),
        );
      },
    );
  }

  /// todo：搜索栏
  _searchBar() {
    return SafeArea(
      child: Container(
        width: Get.width,
        padding: EdgeInsets.symmetric(vertical: 5,horizontal: 15),
        child: Row(
          children: [
            Expanded(
              child: textFieldWidget(
                circular: 5,
                height: 45,
                controller: logic.textEditingControllerSearch,
                bgColor: Colors.grey.shade100,
                hintText: "搜索关键字",
                prefixIcon: Icon(Icons.search,color: Colors.grey,size: 30,),
                onSubmitted: (v){
                  logic.currentIndex = 0;
                  logic.getBodyList();
                }
              ),
            ),
            SizedBox(width: 15,),
            InkWidget.imgAsset("xiangji.png",width: 30,onTap: (){
              Get.to(()=> ReleasePage())!.then((value) => logic.getBodyList());
            }),
          ],
        ),
      ),
    );
  }

  /// todo：内容
  _contentBody() {
    return Expanded(
      child: baseScaffoldWidget(
        onRefresh: ()async{
          logic.getBodyList();
          logic.getSysNotice();
        },
        onLoad: () async{
          print("object");
        },
        loading: logic.loading,
        child: ListView(
          shrinkWrap: true,
          padding: EdgeInsets.all(0),
          children: [
            _adCard(),

            _messageBar(),

            _tabBar(),

            ListView(
              physics: NeverScrollableScrollPhysics(),
              padding: EdgeInsets.all(0),
              shrinkWrap: true,
              children: List.generate(logic.circleListDataList.length, (index){
                return _cardItem(index);
              }),
            ),
          ],
        ),
      ),
    );
  }

  /// todo：AD 轮播图
  _adCard() {
    return Container(
      width: Get.width,
      // 9：16 的比例
      height: (Get.width - 30) / (16/9), 
      child: logic.squareADData!.length == 0 ? SizedBox(): ClipRRect(
        child: Swiper(
          pagination: SwiperPagination(
            builder: DotSwiperPaginationBuilder(
              color: Colors.grey,
              activeColor: Colors.black,
              size: 9.0,
              activeSize: 12.0,
            ),
          ),
          autoplay: true,
          index: 0,
          itemBuilder: (BuildContext context, int index) {
            return InkWidget.imgNet("${logic.squareADData![index].url}",fit: BoxFit.cover,width: Get.width - 30,height: (Get.width - 30) / (16/9),);
          },
          itemCount: logic.squareADData!.length,
        ),
        borderRadius: BorderRadius.circular(10),
      ),
      margin: EdgeInsets.symmetric(vertical: 10,horizontal: 15),
    );
  }

  /// todo：公告栏
  _messageBar() {
    String title = logic.sysNoticeData!.length> 0 ? logic.sysNoticeData![0].msgTitle! : '';
    return rowBaseWidget(
      leftText: "系统公告: $title",
      showLine: false,
      bgColor: Colors.grey.shade100,
      margin: EdgeInsets.symmetric(horizontal: 15),
      padding: EdgeInsets.symmetric(horizontal: 15,vertical: 10),
      right: InkWidget.imgAsset("right2.png",width: 15),
      onTap: ()=> Get.to(()=>MessageInfoPage(title: "系统公告",)),
    );
  }

  /// todo：分类选择栏
  _tabBar() {
    return tab(
      height: 60,
      tabs: logic.type,
      currentIndex: logic.currentIndex,
      mainAxisAlignment: MainAxisAlignment.start,
      onTap: (val){
        logic.setCurrentIndex(val);
      }
    );
  }

  /// todo：卡片item
  _cardItem(int index) {
    return InkWell(
      child: Container(
        width: Get.width,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.shade200,
              blurRadius: 2,
              spreadRadius: 5,
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _cardItemUserRow(index),

            InkWidget.title("${logic.circleListDataList[index].postTitle}",fonSize: 16,maxLines: 2),

            InkWidget.text("${logic.circleListDataList[index].postContent}",color: Colors.grey.shade500,fonSize: 14,maxLines: 9999999999),

            /// todo：图片
            Container(
              width: Get.width,
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Wrap(
                alignment: WrapAlignment.spaceBetween,
                runSpacing: 10,
                children: [
                  ...List.generate(logic.circleListDataList[index].postUrls!.length, (imgIndex) {
                    return InkWidget.imgNet(logic.circleListDataList[index].postUrls![imgIndex],onTap: (){
                      Get.to(()=>ShowImageWidget(
                        images: logic.circleListDataList[index].postUrls ?? [],
                        currentIndex: imgIndex, controller: PageController(),
                      ),preventDuplicates: false,);
                    },width: (Get.width - 30 - 20) / 3,height: (Get.width - 30 - 20) / 3,borderRadius: BorderRadius.circular(5));
                  }),
                ],
              ),
            ),

            /// todo：评论点赞
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Row(
                  children: [
                    InkWidget.imgAsset("pl2.png",width: 20,),
                    InkWidget.text(" ${logic.getCount(index)}"),
                  ],
                ),

                InkWell(
                  onTap: () async{
                    logic.praise(logic.circleListDataList[index].postId,index);
                  },
                  child: Row(
                    children: [
                      InkWidget.imgAsset("dz.png",width: 20,color: logic.circleListDataList[index].isPraise! ? null: Colors.grey),
                      InkWidget.text(" ${logic.circleListDataList[index].praiseCount}",height: 1.5),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
        padding: EdgeInsets.all(15),
      ),
      onTap: (){
        Get.to(()=>GuangChangDetailsPage(),arguments:logic.circleListDataList[index].postId )!.then((value) => logic.getBodyList());
      },
    );
  }

  /// todo：卡片user行
  _cardItemUserRow(int index) {
    return Container(
      width: Get.width,
      padding: EdgeInsets.only(bottom: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Row(
              children: [
                InkWidget.imgNet(
                  "${logic.circleListDataList[index].userPic}",
                  fit: BoxFit.cover,
                  width: 55,
                  height: 55,
                  clip: true,
                  onTap: () async{
                    print("进入聊天页面");
                    if(logic.circleListDataList[index].ryUserId==null)return toast("融云id为空，无法通讯");
                    // final String? ryUserId;
                    // final int? friendId;
                    // final int? type; // 1 对话设置 2 添加好友
                    Get.to(()=>ChatSettingPage(
                      ryUserId: logic.circleListDataList[index].ryUserId,
                      friendId: logic.circleListDataList[index].userId,
                      type: 2,
                    ));
                    // Get.to(()=>ChatPage(
                    //   targetId: logic.circleListDataList[index].ryUserId,
                    //   title: logic.circleListDataList[index].nikeName,
                    //   userPic: logic.circleListDataList[index].userPic,
                    //   friendId: logic.circleListDataList[index].userId,
                    // ));
                  }
                ),
                SizedBox(width: 10,),
                Expanded(
                    child: SizedBox(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          InkWidget.title("${logic.circleListDataList[index].nikeName ?? ''}",fonSize: 13,maxLines: 2),
                          InkWidget.text("${logic.circleListDataList[index].releaseTime}",fonSize: 11,color: Colors.grey),
                        ],
                      ),
                      height: 55,
                    )
                ),
                SizedBox(width: 5,),
              ],
            ),
          ),

          // 不能关注自己
          Offstage(
            offstage: logic.circleListDataList[index].userId == Constant.userDetailData!.id,
            child: SizedBox(
              width: 80,
              height: 35,
              child: gradientButton(logic.circleListDataList[index].isAttention!?"已关注":"+关注",onTap: () async{
                if(!logic.circleListDataList[index].isAttention!){
                  BaseEntity baseEntity = await DioService<BaseEntity>().clickFollow({
                    "beFollowUserId": logic.circleListDataList[index].userId,
                  });
                  if(baseEntity.code == 0){
                    logic.circleListDataList[index].isAttention = !logic.circleListDataList[index].isAttention!;
                    logic.update();
                  }
                }else{
                  BaseEntity cancelFollow = await DioService<BaseEntity>().cancelFollow({
                    "beFollowUserId": logic.circleListDataList[index].userId,
                  });
                  if(cancelFollow.code == 0){
                    logic.circleListDataList[index].isAttention = !logic.circleListDataList[index].isAttention!;
                    logic.update();
                  }
                }
              },bgColor: logic.circleListDataList[index].isAttention! ? Colors.grey:null),
            ),
          )
        ],
      ),
    );
  }


  @override
  void dispose() {
    Get.delete<SquareLogic>();
    super.dispose();
  }
}